
package com.groupbuying.cheetah.service.impl;


import com.groupbuying.cheetah.constants.CheetahOrderFinanceorderEnumConstants;
import com.groupbuying.cheetah.constants.RedisKeyEnumConstants;
import com.groupbuying.cheetah.constants.TmpOrderFlowEnumConstants;
import com.groupbuying.cheetah.constants.TmpOrderPayEnumConstants;
import com.groupbuying.cheetah.domain.*;
import com.groupbuying.cheetah.mq.CheetahMQConfig;
import com.groupbuying.cheetah.service.*;
import com.groupbuying.cheetah.utils.JsonUtils;
import com.groupbuying.cheetah.utils.apiresult.ApiResult;
import com.groupbuying.cheetah.utils.apiresult.ApiResultCode;
import com.groupbuying.cheetah.utils.redis.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class MqManagentServiceImpl implements MqManagentService {

    public static final Logger logger = LoggerFactory.getLogger(MqManagentServiceImpl.class);

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    CheetahOrderFinanceorderService orderFinanceorderService;

    @Autowired
    CheetahOrderStoremoneyflowService orderStoremoneyflowService;

    @Autowired
    private CheetahTmpOrderPayService cheetahTmpOrderPayService;

    @Autowired
    private CheetahTmpOrderSettleService cheetahTmpOrderSettleService;

    @Autowired
    private CheetahTmpOrderFlowService cheetahTmpOrderFlowService;
    @Override
    public ApiResult saveOrderFinanceorder(String orderId,String type) {
        String RedisKey;
        if(CheetahMQConfig.ORDER_PAYMENT_REFUND_TAG.equals(type)){
            RedisKey = RedisKeyEnumConstants.ENUM_CHEETAH_ORDER_PAYMENT_REFUND+orderId;
        }else{
            RedisKey = RedisKeyEnumConstants.ENUM_CHEETAH_ORDER_PAYMENT_INQUIRY + orderId;
        }
        //判断MQ是否重复
        if(redisUtils.isHasKey(RedisKey)){
            logger.error("OrderSettlementServiceImpl-->SaveOrderFinanceorder "+orderId+ " consum already committed");
            return ApiResult.failure();
        }
        List<CheetahOrderFinanceorderDO> orderFinanceorderDOList = orderFinanceorderService.getFinanceorderDO(orderId);
        logger.error("OrderSettlementServiceImpl-->SaveOrderFinanceorder "+orderId+" getFinanceorderDO result:::"+JsonUtils.objectToJson(orderFinanceorderDOList));
        if(null == orderFinanceorderDOList || orderFinanceorderDOList.size() == 0){
            logger.error("OrderSettlementServiceImpl-->SaveOrderFinanceorder "+orderId+" orderFinanceorderDOList is null");
            redisUtils.delKey(RedisKey);
            return ApiResult.failure(ApiResultCode.RECONSUMELATER.code(),ApiResultCode.RECONSUMELATER.message());
        }
        //分账成功后将mq信息存入redis，供mq去重判断使用
        redisUtils.setKey(RedisKey,orderId,180);

        Iterator<CheetahOrderFinanceorderDO> iterator = orderFinanceorderDOList.iterator();
        while (iterator.hasNext()) {
            CheetahOrderFinanceorderDO order = iterator.next();
            if(CheetahOrderFinanceorderEnumConstants.ENUM_PAYTYPE_CUR.equals(order.getPaytype())){
                order.setPaymoney(order.getPayCur());
            }else if(TmpOrderFlowEnumConstants.ENUM_PAYTYPE_BAL.equals(order.getPaytype())){
                order.setPaymoney(order.getPayBalance());
            }else{
                order.setPaymoney(order.getPaymoney());
            }
            if(CheetahMQConfig.ORDER_PAYMENT_REFUND_TAG.equals(type)){
                if ("支付成功".equals(order.getOrderstate())) {
                    iterator.remove();
                }
            }
        }

        logger.error("OrderSettlementServiceImpl-->SaveOrderFinanceorder "+orderId+" saveList params:::"+JsonUtils.objectToJson(orderFinanceorderDOList));
        int count = orderFinanceorderService.saveList(orderFinanceorderDOList);

        if(count <= 0){
            logger.error("OrderSettlementServiceImpl-->SaveOrderFinanceorder "+orderId+" fail:count<0 orderFinanceorderDO:"+ JsonUtils.objectToJson(orderFinanceorderDOList));
            return ApiResult.failure();
        }
        return ApiResult.success();
    }

    @Override
    public ApiResult saveOrderStoremoneyflow(String orderId) {
        String RedisKey = RedisKeyEnumConstants.ORDER_STORE_MONEY_FLOW_TAG+orderId;
        //判断MQ是否重复
        if(redisUtils.isHasKey(RedisKey)){
            logger.error("OrderSettlementServiceImpl-->saveOrderStoremoneyflow "+orderId+ " consum already committed");
            return ApiResult.failure();
        }
        List<CheetahOrderStoremoneyflowDO> orderStoremoneyflowDOList = orderStoremoneyflowService.getOrderStoremoneyflowDOList(orderId);
        if(null == orderStoremoneyflowDOList || orderStoremoneyflowDOList.size() == 0){
            logger.error("OrderSettlementServiceImpl-->saveOrderStoremoneyflow "+orderId+" orderStoremoneyflowDOList is null");
            redisUtils.delKey(RedisKey);
            return ApiResult.failure(ApiResultCode.RECONSUMELATER.code(),ApiResultCode.RECONSUMELATER.message());
        }
        //分账成功后将mq信息存入redis，供mq去重判断使用
        redisUtils.setKey(RedisKey,orderId,180);
        logger.error("OrderSettlementServiceImpl-->saveOrderStoremoneyflow "+orderId+" orderStoremoneyflowDOList:"+JsonUtils.objectToJson(orderStoremoneyflowDOList));
        int count = orderStoremoneyflowService.saveList(orderStoremoneyflowDOList);
        if(count < 0){
            logger.error("OrderSettlementServiceImpl-->saveOrderStoremoneyflow "+orderId+"save fail:count<0 orderFinanceorderDO:"+ JsonUtils.objectToJson(orderStoremoneyflowDOList));
            return ApiResult.failure();
        }
        return ApiResult.success();
    }

    @Override
    public ApiResult saveTmpOrderPayRefund(String orderId) {
        logger.error("MqManagentServiceImpl.saveTmpOrderPayRefund()--请求到的orderId:"+orderId);
        String RedisKey = RedisKeyEnumConstants.ENUM_TMP_ORDER_PAY_REFUND+orderId;
        //判断MQ是否重复
        if(redisUtils.isHasKey(RedisKey)){
            logger.error("MqManagentServiceImpl-->saveTmpOrderPayRefund "+orderId+ " consum already committed");
            return ApiResult.failure();
        }
        //分账成功后将mq信息存入redis，供mq去重判断使用
        redisUtils.setKey(RedisKey,orderId,180);
        List<CheetahTmpOrderPayDO>  tmpOrderPayList = cheetahTmpOrderPayService.getTmpOrderPayList(orderId);
        if(null == tmpOrderPayList || tmpOrderPayList.size() == 0){
            logger.error("MqManagentServiceImpl-->saveTmpOrderPayRefund "+orderId+" orderStoremoneyflowDOList is null");
            redisUtils.delKey(RedisKey);
            return ApiResult.failure(ApiResultCode.RECONSUMELATER.code(),ApiResultCode.RECONSUMELATER.message());
        }
        logger.error("MqManagentServiceImpl-->saveTmpOrderPayRefund "+orderId+" saveTmpOrderPay:"+JsonUtils.objectToJson(tmpOrderPayList));
        tmpOrderPayList.get(0).setOrderState("已退款");
        int count = cheetahTmpOrderPayService.save(tmpOrderPayList.get(0));
        if(count < 0){
            logger.error("MqManagentServiceImpl-->saveTmpOrderPayRefund "+orderId+"save fail:count<0 saveTmpOrderPay:"+ JsonUtils.objectToJson(tmpOrderPayList));
        }
        return ApiResult.success();
    }

    @Override
    public ApiResult saveTmpOrderPay(String orderId) {
        logger.error("MqManagentServiceImpl.saveTmpOrderPay()--请求到的orderId:"+orderId);
        String RedisKey = RedisKeyEnumConstants.CHEETAH_TMP_ORDER_PAY+orderId;
        //判断MQ是否重复
        if(redisUtils.isHasKey(RedisKey)){
            logger.error("MqManagentServiceImpl-->saveTmpOrderPay "+orderId+ " consum already committed");
            return ApiResult.failure();
        }
        List<CheetahTmpOrderPayDO> tmpOrderPayList =new ArrayList<CheetahTmpOrderPayDO>();
        String orderType = orderId.substring(4,7);
        if(orderType.equalsIgnoreCase("002")){
            //积分换购
            tmpOrderPayList = cheetahTmpOrderPayService.getTmpGYOrderPayList(orderId);
        }else{
            tmpOrderPayList = cheetahTmpOrderPayService.getTmpOrderPayList(orderId);
        }
        if(null == tmpOrderPayList || tmpOrderPayList.size() == 0){
            logger.error("MqManagentServiceImpl-->saveTmpOrderPay "+orderId+" orderStoremoneyflowDOList is null");
            redisUtils.delKey(RedisKey);
            return ApiResult.failure(ApiResultCode.RECONSUMELATER.code(),ApiResultCode.RECONSUMELATER.message());
        }
        //分账成功后将mq信息存入redis，供mq去重判断使用
        redisUtils.setKey(RedisKey,orderId,180);
        logger.error("MqManagentServiceImpl-->saveTmpOrderPay "+orderId+" saveTmpOrderPay:"+JsonUtils.objectToJson(tmpOrderPayList));
        CheetahTmpOrderPayDO orderPay = tmpOrderPayList.get(0);
        orderPay.setOrderState("已支付");
        if(TmpOrderFlowEnumConstants.ENUM_PAYTYPE_CUR.equals(orderPay.getPayType())){
            orderPay.setFinalPayPrice(orderPay.getPayCur());
        }else if(TmpOrderFlowEnumConstants.ENUM_PAYTYPE_BAL.equals(orderPay.getPayType())){
            orderPay.setFinalPayPrice(orderPay.getPayBalance());
        }else{
            orderPay.setFinalPayPrice(orderPay.getPayMoney());
        }
        int count = cheetahTmpOrderPayService.save(orderPay);
        if(count < 0){
            logger.error("MqManagentServiceImpl-->saveTmpOrderPay "+orderId+"save fail:count<0 saveTmpOrderPay:"+ JsonUtils.objectToJson(tmpOrderPayList));
        }
        return ApiResult.success();
    }

    @Override
    public ApiResult saveTmpOrderSettleRefund(String orderId) {
        logger.error("MqManagentServiceImpl.saveTmpOrderSettleRefund()--请求到的orderId:"+orderId);
        String RedisKey = RedisKeyEnumConstants.ENUM_TMP_ORDER_SETTLE_REFUND+orderId;
        //判断MQ是否重复
        if(redisUtils.isHasKey(RedisKey)){
            logger.error("MqManagentServiceImpl-->saveTmpOrderSettleRefund "+orderId+ " consum already committed");
            return ApiResult.failure();
        }
        //分账成功后将mq信息存入redis，供mq去重判断使用
        redisUtils.setKey(RedisKey,orderId,180);
        List<CheetahTmpOrderSettleDO> tmpOrderSettleList = cheetahTmpOrderSettleService.getCheetahTmpOrderSettleList(orderId);
        if(null == tmpOrderSettleList || tmpOrderSettleList.size() == 0){
            logger.error("MqManagentServiceImpl-->saveTmpOrderSettleRefund "+orderId+" tmpOrderSettleList is null");
            redisUtils.delKey(RedisKey);
            return ApiResult.failure(ApiResultCode.RECONSUMELATER.code(),ApiResultCode.RECONSUMELATER.message());
        }
        logger.error("MqManagentServiceImpl-->saveTmpOrderSettleRefund "+orderId+" saveTmpOrderSettle:"+JsonUtils.objectToJson(tmpOrderSettleList));
        tmpOrderSettleList.get(0).setOrderState("已退款");
        BigDecimal PaymentOfChannelFee = tmpOrderSettleList.get(0).getPaymentOfChannelFee().multiply(new BigDecimal("-1"));
        tmpOrderSettleList.get(0).setPaymentOfChannelFee(PaymentOfChannelFee);
        int count = cheetahTmpOrderSettleService.save(tmpOrderSettleList.get(0));
        if(count < 0){
            logger.error("MqManagentServiceImpl-->saveTmpOrderSettleRefund "+orderId+"save fail:count<0 tmpOrderSettle:"+ JsonUtils.objectToJson(tmpOrderSettleList));
        }
        return ApiResult.success();
    }

    @Override
    public ApiResult saveTmpOrderSettle(String orderId) {
        logger.error("MqManagentServiceImpl.saveTmpOrderSettle()--请求到的orderId:"+orderId);
        String RedisKey = RedisKeyEnumConstants.CHEETAH_TMP_ORDER_PAY_SETTLE+orderId;
        //判断MQ是否重复
        if(redisUtils.isHasKey(RedisKey)){
            logger.error("MqManagentServiceImpl-->saveTmpOrderSettle "+orderId+ " consum already committed");
            return ApiResult.failure();
        }
        List<CheetahTmpOrderSettleDO> tmpOrderSettleList =new ArrayList<CheetahTmpOrderSettleDO>();
        String orderType = orderId.substring(4,7);
        if(orderType.equalsIgnoreCase("002")){
            //积分换购
            tmpOrderSettleList = cheetahTmpOrderSettleService.getCheetahTmpGYOrderSettleList(orderId);
        }else{
            tmpOrderSettleList = cheetahTmpOrderSettleService.getCheetahTmpOrderSettleList(orderId);
        }
        if(null == tmpOrderSettleList || tmpOrderSettleList.size() == 0){
            logger.error("MqManagentServiceImpl-->saveTmpOrderSettle "+orderId+" tmpOrderSettleList is null");
            redisUtils.delKey(RedisKey);
            return ApiResult.failure(ApiResultCode.RECONSUMELATER.code(),ApiResultCode.RECONSUMELATER.message());
        }
        //分账成功后将mq信息存入redis，供mq去重判断使用
        redisUtils.setKey(RedisKey,orderId,180);
        logger.error("MqManagentServiceImpl-->saveTmpOrderSettle "+orderId+" saveTmpOrderSettle:"+JsonUtils.objectToJson(tmpOrderSettleList));
        tmpOrderSettleList.get(0).setOrderState("已支付");
        int count = cheetahTmpOrderSettleService.save(tmpOrderSettleList.get(0));
        if(count < 0){
            logger.error("MqManagentServiceImpl-->saveTmpOrderSettle "+orderId+"save fail:count<0 tmpOrderSettle:"+ JsonUtils.objectToJson(tmpOrderSettleList));
        }
        return ApiResult.success();
    }

    @Override
    public ApiResult saveTmpOrderFlow(String orderId) {
        logger.error("MqManagentServiceImpl.saveTmpOrderFlow()--请求到的orderId:"+orderId);
        String RedisKey = RedisKeyEnumConstants.CHEETAH_TMP_ORDER_FLOW+orderId;
        //判断MQ是否重复
        if(redisUtils.isHasKey(RedisKey)){
            logger.error("MqManagentServiceImpl-->saveTmpOrderFlow "+orderId+ " consum already committed");
            return ApiResult.failure();
        }
        //分账成功后将mq信息存入redis，供mq去重判断使用
        redisUtils.setKey(RedisKey,orderId,180);
        List<CheetahTmpOrderFlowDO> tmpOrderFlowList = cheetahTmpOrderFlowService.getCheetahTmpOrderFlowList(orderId);
        if(null == tmpOrderFlowList || tmpOrderFlowList.size() == 0){
            logger.error("MqManagentServiceImpl-->saveTmpOrderFlow "+orderId+" tmpOrderSettleList is null");
            redisUtils.delKey(RedisKey);
            return ApiResult.failure(ApiResultCode.RECONSUMELATER.code(),ApiResultCode.RECONSUMELATER.message());
        }
        logger.error("MqManagentServiceImpl-->saveTmpOrderFlow "+orderId+" saveTmpOrderFlow:"+JsonUtils.objectToJson(tmpOrderFlowList));
        CheetahTmpOrderFlowDO orderFlow =tmpOrderFlowList.get(0);
        if(TmpOrderFlowEnumConstants.ENUM_PAYTYPE_CUR.equals(orderFlow.getPayType())){
            orderFlow.setFinalPayPrice(orderFlow.getPayCur());
        }else if(TmpOrderFlowEnumConstants.ENUM_PAYTYPE_BAL.equals(orderFlow.getPayType())){
            orderFlow.setFinalPayPrice(orderFlow.getPayBalance());
        }else{
            orderFlow.setFinalPayPrice(orderFlow.getPayMoney());
        }
        orderFlow.setOrderState("已支付");
        logger.error("MqManagentServiceImpl-->saveTmpOrderFlow "+orderId+" saveTmpOrderFlow:"+orderFlow);
        int count = cheetahTmpOrderFlowService.save(orderFlow);
        if(count < 0){
            logger.error("MqManagentServiceImpl-->saveTmpOrderFlow "+orderId+"save fail:count<0 saveTmpOrderFlow:"+ JsonUtils.objectToJson(tmpOrderFlowList));
        }
        return ApiResult.success();
    }

    @Override
    public ApiResult saveTmpOrderFlowRefund(String orderId) {
        logger.error("MqManagentServiceImpl.saveTmpOrderFlowRefund()--请求到的orderId:"+orderId);
        String redisKey = RedisKeyEnumConstants.ENUM_TMP_ORDER_FLOW_REFUND+orderId;
        //判断MQ是否重复
        if(redisUtils.isHasKey(redisKey)){
            logger.error("MqManagentServiceImpl-->saveTmpOrderFlowRefund "+orderId+ " consum already committed");
            return ApiResult.failure();
        }
        //分账成功后将mq信息存入redis，供mq去重判断使用
        redisUtils.setKey(redisKey,orderId,180);
        List<CheetahTmpOrderFlowDO> tmpOrderFlowRefundList = cheetahTmpOrderFlowService.getCheetahTmpOrderFlowList(orderId);
        if(null == tmpOrderFlowRefundList || tmpOrderFlowRefundList.size() == 0){
            logger.error("MqManagentServiceImpl-->saveTmpOrderFlowRefund "+orderId+" tmpOrderSettleList is null");
            redisUtils.delKey(redisKey);
            return ApiResult.failure(ApiResultCode.RECONSUMELATER.code(),ApiResultCode.RECONSUMELATER.message());
        }
        for(CheetahTmpOrderFlowDO orderFlow:tmpOrderFlowRefundList){
            if(TmpOrderFlowEnumConstants.ENUM_PAYTYPE_CUR.equals(orderFlow.getPayType())){
                orderFlow.setFinalPayPrice(orderFlow.getPayCur());
            }else if(TmpOrderFlowEnumConstants.ENUM_PAYTYPE_BAL.equals(orderFlow.getPayType())){
                orderFlow.setFinalPayPrice(orderFlow.getPayBalance());
            }else{
                orderFlow.setFinalPayPrice(orderFlow.getPayMoney());
            }
            BigDecimal finalPayPrice =orderFlow.getFinalPayPrice()== null ? new BigDecimal("0.00"):orderFlow.getFinalPayPrice();
            BigDecimal orderPrice =orderFlow.getOrderPrice()== null ? new BigDecimal("0.00"):orderFlow.getOrderPrice();
            BigDecimal platformIncome =orderFlow.getPlatformIncome()== null ? new BigDecimal("0.00"):orderFlow.getPlatformIncome();
            BigDecimal storeIncome =orderFlow.getStoreIncome()== null ? new BigDecimal("0.00"):orderFlow.getStoreIncome();
            BigDecimal bonusPoints =orderFlow.getBonusPoints()== null ? new BigDecimal("0.00"):orderFlow.getBonusPoints();
            BigDecimal paymentOfChannelFee =orderFlow.getPaymentOfChannelFee()== null ? new BigDecimal("0.00"):orderFlow.getPaymentOfChannelFee();

            orderFlow.setFinalPayPrice(finalPayPrice.multiply(new BigDecimal("-1")));
            orderFlow.setOrderPrice(orderPrice.multiply(new BigDecimal("-1")));
            orderFlow.setPlatformIncome(platformIncome.multiply(new BigDecimal("-1")));
            orderFlow.setStoreIncome(storeIncome.multiply(new BigDecimal("-1")));
            orderFlow.setBonusPoints(bonusPoints.multiply(new BigDecimal("-1")));
            orderFlow.setPaymentOfChannelFee(paymentOfChannelFee.multiply(new BigDecimal("-1")));
        }

        logger.error("MqManagentServiceImpl-->saveTmpOrderFlowRefund "+orderId+" saveTmpOrderFlow:"+JsonUtils.objectToJson(tmpOrderFlowRefundList));
        tmpOrderFlowRefundList.get(0).setOrderState("已退款");
        int count = cheetahTmpOrderFlowService.save(tmpOrderFlowRefundList.get(0));
        if(count < 0){
            logger.error("MqManagentServiceImpl-->saveTmpOrderFlowRefund "+orderId+"save fail:count<0 saveTmpOrderFlow:"+ JsonUtils.objectToJson(tmpOrderFlowRefundList));
        }
        return ApiResult.success();
    }
}
